package com.hanter.android.radwidget.cupertino;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;

import java.util.ArrayList;
import java.util.List;

public class TabContainer extends FrameLayout implements CupertinoTabBar.OnTabChangeListener {

    private static final String TAG = "TabContainer";

    @Deprecated
    public static final int BEHAVIOR_SET_USER_VISIBLE_HINT = 0;

    /**
     * Indicates that only the current fragment will be in the {@link Lifecycle.State#RESUMED}
     * state. All other Fragments are capped at {@link Lifecycle.State#STARTED}.
     */
    public static final int BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT = 1;

    public static final int FRAGMENT_DISPLAY_SHOW = 0;
    public static final int FRAGMENT_DISPLAY_ATTACH = 1;

    private int fragmentDisplayMode;
    private int behavior = BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;
    private FragmentManager fm;
    @IdRes
    private int containerId;
    private boolean attached;

    private int currentTab = -1;
    private List<TabInfo> tabs = new ArrayList<>(2);
    private TabInfo lastTab;
    @Nullable
    private TabBar tabBar;

    static final class TabInfo {
        @NonNull
        final String tag;
        @NonNull
        final Class<?> clazz;
        @Nullable
        final Bundle args;
        Fragment fragment;

        TabInfo(@NonNull String tag, @NonNull Class<?> clazz, @Nullable Bundle args) {
            this.tag = tag;
            this.clazz = clazz;
            this.args = args;
        }
    }

    static class SavedState extends BaseSavedState {
        String curTab;

        SavedState(Parcelable superState) {
            super(superState);
        }

        SavedState(Parcel in) {
            super(in);
            curTab = in.readString();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeString(curTab);
        }

        @Override
        public String toString() {
            return "TabContainer.SavedState{"
                    + Integer.toHexString(System.identityHashCode(this))
                    + " curTab=" + curTab + "}";
        }

        public static final Creator<SavedState> CREATOR
                = new Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }


    public TabContainer(@NonNull Context context) {
        super(context);
    }

    public TabContainer(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TabContainer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    public TabContainer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public void setup(@NonNull FragmentManager fm) {
        setup(fm, View.NO_ID);
    }

    public void setup(@NonNull FragmentManager fm, @IdRes int id) {
        this.fm = fm;
        if (id == View.NO_ID) {
            id = getId();
            if (id == View.NO_ID) {
                id = generateViewId();
                this.setId(id);
            }
        }
        this.containerId = id;
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        final String currentTag = getCurrentTabTag();

        // Go through all tabs and make sure their fragments match
        // the correct state.
        FragmentTransaction ft = null;
        for (int i = 0, count = tabs.size(); i < count; i++) {
            final TabInfo tab = tabs.get(i);
            tab.fragment = fm.findFragmentByTag(tab.tag);
            if (tab.fragment != null && !tab.fragment.isDetached()) {
                if (tab.tag.equals(currentTag)) {
                    // The fragment for this tab is already there and
                    // active, and it is what we really want to have
                    // as the current tab.  Nothing to do.
                    this.lastTab = tab;
                } else {
                    // This fragment was restored in the active state,
                    // but is not the current tab.  Deactivate it.
                    if (ft == null) {
                        ft = fm.beginTransaction();
                    }
                    hideFragment(ft, tab.fragment);
                }
            }
        }

        // We are now ready to go.  Make sure we are switched to the
        // correct tab.
        this.attached = true;
        ft = doTabChanged(currentTag, ft);
        commitTransaction(ft);
        fm.executePendingTransactions();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        this.attached = false;
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);
        ss.curTab = getCurrentTabTag();
        return ss;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (!(state instanceof SavedState)) {
            super.onRestoreInstanceState(state);
            return;
        }
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());
        setCurrentTabByTag(ss.curTab);
    }

    public void addTab(String tag, Class<?> clazz, Bundle args) {
        final TabInfo info = new TabInfo(tag, clazz, args);

        if (attached) {
            // If we are already attached to the window, then check to make
            // sure this tab's fragment is inactive if it exists.  This shouldn't
            // normally happen.
            info.fragment = fm.findFragmentByTag(tag);
            if (info.fragment != null && !info.fragment.isDetached()) {
                final FragmentTransaction ft = fm.beginTransaction();
                ft.hide(info.fragment);
                commitTransaction(ft);
            }
        }

        this.tabs.add(info);

        if (currentTab == -1) {
            setCurrentTab(0);
        }
    }

    @Override
    public void onTabChanged(TabBarItem item) {
        setCurrentTabByTag(item.getTag());
    }

    protected void onTabChangedInternal(String tag) {
        if (attached) {
            final FragmentTransaction ft = doTabChanged(tag, null);
            commitTransaction(ft);
        }
    }

    @SuppressWarnings("UnusedReturnValue")
    protected int commitTransaction(@Nullable FragmentTransaction ft) {
        if (ft != null) {
            return ft.commitAllowingStateLoss();
        } else {
            return -1;
        }
    }

    @Nullable
    private FragmentTransaction doTabChanged(@Nullable String tag,
                                             @Nullable FragmentTransaction ft) {
        Log.d(TAG, "doTabChanged");

        final TabInfo newTab = getTabInfoForTag(tag);
        if (lastTab != newTab) {
            if (ft == null) {
                ft = fm.beginTransaction();
            }

            if (lastTab != null) {
                if (lastTab.fragment != null) {
                    hideFragment(ft, lastTab.fragment);
                }
            }

            if (newTab != null) {
                if (newTab.fragment == null) {
                    newTab.fragment = fm.getFragmentFactory().instantiate(
                            getContext().getClassLoader(), newTab.clazz.getName());
                    newTab.fragment.setArguments(newTab.args);

                    Log.d(TAG, "add fragment: " + tag);

                    if (behavior == BEHAVIOR_SET_USER_VISIBLE_HINT) {
                        newTab.fragment.setUserVisibleHint(true);
                    }

                    ft.add(containerId, newTab.fragment, newTab.tag);

                    if (behavior == BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
                        ft.setMaxLifecycle(newTab.fragment, Lifecycle.State.RESUMED);
                    }
                } else {
                    Log.d(TAG, "show fragment: " + tag);
                    showFragment(ft, newTab.fragment);
                }
            }

            lastTab = newTab;
        }

        return ft;
    }

    private void showFragment(FragmentTransaction ft, Fragment f) {
        if (fragmentDisplayMode == FRAGMENT_DISPLAY_ATTACH) {
            ft.attach(f);
        } else {
            ft.show(f);
        }

        if (behavior == BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            ft.setMaxLifecycle(f, Lifecycle.State.RESUMED);
        } else {
            f.setUserVisibleHint(true);
        }
    }

    private void hideFragment(FragmentTransaction ft, Fragment f) {
        if (fragmentDisplayMode == FRAGMENT_DISPLAY_ATTACH) {
            ft.detach(f);
        } else {
            ft.hide(f);
        }

        if (behavior == BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            ft.setMaxLifecycle(f, Lifecycle.State.STARTED);
        } else {
            f.setUserVisibleHint(false);
        }
    }

    public void setCurrentTab(int index) {
        if (index < 0 || index >= getTabCount() || index == currentTab) {
            return;
        }

        this.currentTab = index;

        if (this.tabBar != null) {
            this.tabBar.setCurrentTab(index);
        }

        onTabChangedInternal(getCurrentTabTag());
    }

    public void setCurrentTabByTag(String tag) {
        for (int i = 0, count = tabs.size(); i < count; i++) {
            final TabInfo tab = tabs.get(i);
            if (tab.tag.equals(tag)) {
                setCurrentTab(i);
                return;
            }
        }
    }

    public int getTabCount() {
        return this.tabs.size();
    }

    public String getCurrentTabTag() {
        if (currentTab >= 0 && currentTab < tabs.size()) {
            return tabs.get(currentTab).tag;
        }
        return null;
    }

    @Nullable
    private TabInfo getTabInfoForTag(String tabId) {
        for (int i = 0, count = tabs.size(); i < count; i++) {
            final TabInfo tab = tabs.get(i);
            if (tab.tag.equals(tabId)) {
                return tab;
            }
        }
        return null;
    }

    public void bindTabBar(CupertinoTabBar tabBar) {
        this.tabBar = tabBar;
        if (tabBar != null) {
            tabBar.setCurrentTabByTag(getCurrentTabTag());
            tabBar.setOnTabChangeListener(this);
        }
    }

}
